<?php

namespace app\api\controller;

use app\common\model\Tags;
use think\facade\Filesystem;

class Member
{

    public $memberModel;
    public $memberData;

    public function __construct()
    {
        $token = post_param('token');
        if (empty($token)) output_error('非法访问~');
        $this->memberModel = new \app\common\model\Member();
        $this->memberData = $this->memberModel->where('member_token', '=', $token)->find();
        if (empty($this->memberData)) output_error('令牌无效~');
    }

    public function getData()
    {
        output_data($this->memberData);
    }

    public function addTags()
    {
        //数据校验
        $title = post_param('title');
        $link = post_param('link');
        if (empty($title) || empty($link)) output_error_param();
        $tagsModel = new Tags();
        $condition = array();
        $condition[] = ['member_id', '=', $this->memberData['member_id']];
        $condition[] = ['tags_title', '=', $title];
        $condition[] = ['tags_link', '=', $link];
        $data = $tagsModel->where($condition)->find();
        if (!empty($data)) output_error('此书签已存在');
        //入库
        $data = array();
        $data['member_id'] = $this->memberData['member_id'];
        $data['tags_title'] = $title;
        $data['tags_link'] = $link;
        $data['add_time'] = time();
        $tagsModel->insert($data);
        output_success();
    }

    public function getTags()
    {
        $keyword = post_param('keyword');//接受Android客户端传过来胡keyword参数
        //构建查询条件
        $condition = array();
        $condition[] = ['member_id', '=', $this->memberData['member_id']];
        //如果keyword参数不为空，就把它加到条件数组
        if (!empty($keyword)) $condition[] = ['tags_title', 'like', '%' . $keyword . '%'];
        //实例化tags模型
        $tagsModel = new Tags();
        //执行对应的sql语句
        $data = $tagsModel->where($condition)->select();
        //输出数据
        output_data($data);
    }

    //此接口的作用，用于根据ID删除一个书签
    public function delete()
    {
        //接受ID
        $id = post_param('id');
        if (empty($id)) output_error_param();//如果未传ID或者ID是空的，直接输出错误
        //校验通过后要执行的代码
        $tagsModel = new Tags();//实例化tags模型
        $tagsModel->where('tags_id', '=', $id)->delete();//构建SQL语句并执行
        //输出成功标识
        output_success();
    }

    public function upload()
    {
        //接受前端传过来的文件
        $file = request()->file('file');
        $savename = Filesystem::disk('public')->putFile('', $file, 'uniqid');
        $update = array();
        $update['member_avatar'] = $savename;
        $this->memberModel->where('member_id', '=', $this->memberData['member_id'])->update($update);
        output_success();
    }

}
